package io.kiki.stack.netty.processor;

import io.kiki.stack.netty.channelManager.ChannelContext;
import io.kiki.stack.netty.command.Command;
import io.kiki.stack.netty.util.InetSocketAddressUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;


@Slf4j
@Setter
@Getter
public class ProcessTask<T extends Command> implements Runnable {

    private final AbstractProcessor abstractProcessor;
    ChannelContext channelContext;
    T msg;

    public ProcessTask(ChannelContext channelContext, T msg, AbstractProcessor abstractProcessor) {
        this.abstractProcessor = abstractProcessor;
        this.channelContext = channelContext;
        this.msg = msg;
    }

    @Override
    public void run() {
        try {
            abstractProcessor.doProcess(channelContext, msg);
        } catch (Throwable e) {
            //protect the thread running this task
            String remotingAddress = InetSocketAddressUtil.parseRemoteAddress(channelContext.getChannelHandlerContext().channel());
            log.error("Exception caught when process rpc request command in AbstractRemotingProcessor, Id=" + msg.getId() + "! Invoke source address is [" + remotingAddress + "].", e);
        }
    }

}
